package com.jz.yanshe.ui;

import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jz.yanshe.adapter.TypeAdapter;
import com.jz.yanshe.base.BaseActivity;
import com.jz.yanshe.util.ImageLoaderHelper;
import com.jz.yanshe.util.PreferencesHelper;

import com.jz.jd.rest.business.RestProxy;
import com.jz.jd.rest.exception.BusinessException;
import com.jz.jd.rest.response.BaseResponse;
import com.jz.jd.rest.response.Goods;
import com.jz.jd.rest.response.StyleResponse;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import com.jz.yanshe.R;

/**
 * Created by Administrator on 2018/3/6.
 */

public class MatchActivity extends BaseActivity {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    MyAdapter myAdapter = new MyAdapter();
    ArrayList<Goods> list;

    public String style_color;

    int count = 0;

    @Override
    protected void initViews() {
        recyclerView.setAdapter(myAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = 15;
            }
        });
    }

    @Override
    protected void initData() {
        list = (ArrayList<Goods>) getIntent().getSerializableExtra("list");
        count = list.size();
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_match;
    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {


        @Override
        public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_match, parent, false));
            return holder;
        }

        @Override
        public void onBindViewHolder(final Holder holder, final int position) {

            ImageLoaderHelper.getInstance().GlideImageLoader(MatchActivity.this, list.get(position).goods_icon, holder.img_goods);
            holder.tv_price.setText("¥ " + list.get(position).goods_price);
            holder.tv_remain.setText("库存" + list.get(position).goods_inventory + "件");
            holder.tv_goods_name.setText(list.get(position).goods_name);
            holder.btn_minus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Integer.valueOf(holder.tv_goods_num.getText().toString().trim()) > 1) {
                        holder.tv_goods_num.setText((Integer.valueOf(holder.tv_goods_num.getText().toString().trim()) - 1) + "");
                        list.get(position).goods_sale_num = holder.tv_goods_num.getText().toString();
                    }
                }
            });
            holder.btn_plus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    holder.tv_goods_num.setText((Integer.valueOf(holder.tv_goods_num.getText().toString().trim()) + 1) + "");
                    list.get(position).goods_sale_num = holder.tv_goods_num.getText().toString();
                }
            });

            List<StyleResponse.Sizes> listSize = new ArrayList<>();
            final List<StyleResponse.Sizes> listColor = new ArrayList<>();

            final TypeAdapter adapterColor;
            TypeAdapter adapterSize;

            adapterColor = new TypeAdapter(MatchActivity.this, listColor);
            adapterSize = new TypeAdapter(MatchActivity.this, listSize);

            LinearLayoutManager manager1 = new LinearLayoutManager(MatchActivity.this);
            LinearLayoutManager manager2 = new LinearLayoutManager(MatchActivity.this);
            manager1.setOrientation(LinearLayoutManager.HORIZONTAL);
            manager2.setOrientation(LinearLayoutManager.HORIZONTAL);
            holder.recyclerViewColor.setLayoutManager(manager1);
            holder.recyclerViewSize.setLayoutManager(manager2);
            holder.recyclerViewColor.setAdapter(adapterColor);
            holder.recyclerViewSize.setAdapter(adapterSize);

            holder.recyclerViewColor.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                    super.onDraw(c, parent, state);
                }

                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    super.getItemOffsets(outRect, view, parent, state);
                    outRect.bottom = 10;
                    outRect.right = 10;
                }
            });
            holder.recyclerViewSize.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                    super.onDraw(c, parent, state);
                }

                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    super.getItemOffsets(outRect, view, parent, state);
                    outRect.bottom = 10;
                    outRect.right = 10;
                }
            });
            getAllSize(list.get(position).goods_id, listColor, listSize, adapterColor, adapterSize);

            adapterSize.onItemClick = new TypeAdapter.OnItemClick() {

                @Override
                public void onItemClick(String style_color) {
                    System.out.println(style_color + " aaaaaaaaaaaaaa");
                    queryGoodsId(PreferencesHelper.getInstance().getString(MatchActivity.this,"token"),list.get(position).goods_id, style_color, listColor, adapterColor);
                    MatchActivity.this.style_color = style_color;
                    holder.tv_size.setText("已选： "+ MatchActivity.this.style_color);
                }

                @Override
                public void onItemClick() {

                }
            };
            adapterColor.onItemClick = new TypeAdapter.OnItemClick() {
                @Override
                public void onItemClick(String style_color) {
                    for (int i = 0; i < listColor.size(); i++) {
                        if (listColor.get(i).select == 1) {
                            holder.tv_price.setText("¥ " + listColor.get(i).style_price);
                            holder.tv_remain.setText("库存" + listColor.get(i).goods_inventory + "件");
                            list.get(position).goods_style_id = listColor.get(i).goods_style_id;
                            list.get(position).goods_inventory = listColor.get(i).goods_inventory;
                            holder.tv_size.setText("已选： "+ MatchActivity.this.style_color + "   "+style_color);
                        }
                    }
                }

                @Override
                public void onItemClick() {

                }
            };
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            RecyclerView recyclerViewSize;
            RecyclerView recyclerViewColor;

            TextView btn_plus,tv_size, btn_minus, tv_goods_num, tv_price, tv_remain, tv_goods_name;

            ImageView img_goods;

            public Holder(View itemView) {
                super(itemView);
                recyclerViewSize = itemView.findViewById(R.id.recyclerViewSize);
                recyclerViewColor = itemView.findViewById(R.id.recyclerViewColor);
                tv_price = itemView.findViewById(R.id.tv_price);
                tv_remain = itemView.findViewById(R.id.tv_remain);
                tv_goods_num = itemView.findViewById(R.id.tv_goods_num);
                tv_size = itemView.findViewById(R.id.tv_size);
                btn_minus = itemView.findViewById(R.id.btn_minus);
                btn_plus = itemView.findViewById(R.id.btn_plus);
                img_goods = itemView.findViewById(R.id.img_goods);
                tv_goods_name = itemView.findViewById(R.id.tv_goods_name);
            }
        }
    }

    public void getAllSize(String goodsid, final List<StyleResponse.Sizes> listColor, final List<StyleResponse.Sizes> listSize, final TypeAdapter adapterColor, final TypeAdapter adapterSize) {
        RestProxy.getInstance().getAllSize(goodsid, new Observer<StyleResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(StyleResponse styleResponse) {
                listColor.clear();
                listColor.addAll(styleResponse.map.colors);
                for (int i = 0;i<listColor.size();i++){
                    listColor.get(i).select = -1;
                }
                listSize.clear();
                listSize.addAll(styleResponse.map.sizes);
                adapterColor.notifyDataSetChanged();
                adapterSize.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void queryGoodsId(String token,String goodsid, String style_color, final List<StyleResponse.Sizes> listColor, final TypeAdapter adapterColor) {

        RestProxy.getInstance().queryGoodsId(token,goodsid, style_color, new Observer<StyleResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(StyleResponse styleResponse) {
                for (int j = 0; j < listColor.size(); j++) {
                    listColor.get(j).select = -1;
                }


                for (int i = 0; i < styleResponse.map.colorsBySize.size(); i++) {
                    for (int j = 0; j < listColor.size(); j++) {
                        if (listColor.get(j).style_color.equals(styleResponse.map.colorsBySize.get(i).style_color)) {
                            listColor.get(j).select = 0;
                            listColor.get(j).goods_style_id = styleResponse.map.colorsBySize.get(i).goods_style_id;
                            listColor.get(j).goods_inventory = styleResponse.map.colorsBySize.get(i).goods_inventory;
                            listColor.get(j).style_price = styleResponse.map.colorsBySize.get(i).style_price;
                        }
                    }
                }
                adapterColor.notifyDataSetChanged();

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    @OnClick(R.id.btn_confirm)
    void btn_confirm() {
        for (int i = 0; i < list.size(); i++) {
            addShoppingCar(list.get(i).goods_style_id, list.get(i).goods_sale_num,list.get(i).goods_inventory);
        }
//        Toast.makeText(this, "正在添加到购物车", Toast.LENGTH_SHORT).show();
    }

    private void addShoppingCar(String goods_style_id, String goods_num,String goods_inventory) {
        if(goods_style_id == null||goods_style_id.equals(""))
            return;
        if(Integer.valueOf(goods_num)>Integer.valueOf(goods_inventory)){
            Toast.makeText(this, "该宝贝不能购买更多呦", Toast.LENGTH_SHORT).show();
            return;
        }
        RestProxy.getInstance().addShoppingCar(PreferencesHelper.getInstance().getString(MatchActivity.this,"token"), "2", goods_style_id, goods_num, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                count--;
                if (count == 0) {
                    Toast.makeText(MatchActivity.this, "添加成功，在购物车等亲", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }

            @Override
            public void onError(Throwable e) {
                if (e instanceof BusinessException) {
                toLogin(((BusinessException)e).errorCode);}
            }

            @Override
            public void onComplete() {

            }
        });
    }

}
